import actionTypes from "../action/actionTypes";

export default function shoppingReducer(preState = { num: 0, money: 0, data: [], typeNum: [] }, action) {
  let newPreState = {}
  let newData = []
  let newTypeNum = []
  switch (action.type) {
    // 点击加号加入购物车
    case actionTypes.ADD_SHOPPING_CART:
      newPreState.num = preState.num + 1
      newPreState.money = preState.money + action.payload.price
      newData = preState.data.map((item) => {
        if (item.id === action.payload.id) {
          item.num++
        }
        return item
      })
      newTypeNum = preState.typeNum.map((item) => {
        if (item.classId === action.payload.classId) {
          item.number++
        }
        return item
      })
      newPreState.data = newData
      newPreState.typeNum = newTypeNum
      // console.log(newPreState)
      return newPreState
    // 点击减号减购物车
    case actionTypes.DECREASE_SHOPPING_CART:
      newPreState.num = preState.num - 1
      newPreState.money = preState.money - action.payload.price
      newData = preState.data.map((item) => {
        if (item.id === action.payload.id) {
          item.num--
        }
        return item
      })
      newTypeNum = preState.typeNum.map((item) => {
        if (item.classId === action.payload.classId) {
          item.number--
        }
        return item
      })
      newPreState.data = newData
      newPreState.typeNum = newTypeNum
      // console.log(newPreState)
      return newPreState
    // 设置购物车
    case actionTypes.SET_SHOPPING_CART:
      newPreState.num = preState.num + action.payload.num
      newPreState.money = preState.money + (action.payload.num * action.payload.obj.price)
      newData = preState.data.map((item) => {
        if (item.id === action.payload.obj.id) {
          item.num = action.payload.numNow
          if (action.payload.norms) {
            item.norms = action.payload.norms
          }
        }
        return item
      })
      newTypeNum = preState.typeNum.map((item) => {
        if (item.classId === action.payload.obj.classId) {
          item.number = item.number + action.payload.num
        }
        return item
      })
      newPreState.data = newData
      newPreState.typeNum = newTypeNum
      return newPreState
    // 加载初始化所有菜品
    case actionTypes.LOAD_SHOPPING_DATA:
      newPreState.num = preState.num
      newPreState.money = preState.money
      newPreState.data = action.payload.list2
      newPreState.typeNum = action.payload.list
      return newPreState
    // 清空购物车
    case actionTypes.CLEAR_SHOPPING_CART:
      newPreState.num = 0
      newPreState.money = 0
      newData = preState.data.map((item) => {
        item.num = 0
        item.norms = null
        return item
      })
      newTypeNum = preState.typeNum.map((item) => {
        item.number = 0
        return item
      })
      newPreState.data = newData
      newPreState.typeNum = newTypeNum
      return newPreState
    default:
      return preState
  }
}